/*
@Time : 2019/8/24 0024 15:51
@Author : visons
*/
package main

import (
	"fmt"
	"github.com/go-redis/redis"
	"reflect"
	"strconv"
)

func main() {
	client := redis.NewClient(&redis.Options{
		Addr:     "101.132.140.237:6379",
		DB:       0,
		Password: "",
	})

	defer client.Close()

	pong, err := client.Ping().Result()
	if err != nil {
		fmt.Printf("ping error[%s]\n", err.Error())
	}
	fmt.Printf("ping result: %s\n", pong)

	TestStruct(client)
}

type Users struct {
	Id     int64  `json:"id"`
	Name   string `json:"name"`
	Atavar string `json:"atavar"`
}

func TestStruct(client *redis.Client) {

	client.HMSet("u3", map[string]interface{}{"id": 123, "name": "34w", "atavar": "sdfsf"})

	var user Users
	val := client.HGetAll("u3").Val()

	user.Name = val["name"]
	user.Id, _ = strconv.ParseInt(val["id"], 10, 64)
	user.Atavar = val["name"]
	fmt.Println(user)
	data := StructToMap(user)
	fmt.Println(data)
}

func StructToMap(obj interface{}) map[string]interface{} {
	name := reflect.TypeOf(obj)
	value := reflect.ValueOf(obj)

	data := make(map[string]interface{})
	for i := 0; i < name.NumField(); i++ {
		data[name.Field(i).Name] = value.Field(i).Interface()
	}
	return data
}
